package bsf.redis;

import bsf.base.BsfException;
import bsf.system.configparser.ConfigStringParser;
import bsf.system.configparser.ConfigStringParserManager;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis管理类
 */
public class RedisManager {
    private JedisPool getPool(String connectString) {
        try {
            ConfigStringParser<RedisConfig> parser = new ConfigStringParserManager().GetParser(RedisConfig.class);
            RedisConfig config = parser.Parse(connectString, RedisConfig.class);
            JedisPoolConfig c = new JedisPoolConfig();
            c.setMaxTotal(config.MaxActive);
            c.setMaxIdle(config.MaxIdle);
            c.setMaxWaitMillis(config.MaxWait);
            c.setTestOnBorrow(config.TestOnBorrow);

            JedisPool pool = new JedisPool(c, config.Host, config.Port, config.TimeOut, config.Auth);
            return pool;
        } catch (Exception e) {
            throw new BsfException("解析连接字符串并初始化连接池出错",e, this.getClass());
        }
    }

    /**
     * 获取连接池客户端
     *
     * @param connectString ;分隔连接字符串 模板:host=192.168.17.54:6379;auth=;max_active=20;max_idle=5;
     * @return
     */
    public RedisDb getPoolClient(String connectString) {
        JedisPool pool = getPool(connectString);
        Jedis redisclient = pool.getResource();
        RedisDb db = new RedisDb(redisclient, pool);
        return db;
    }

    /**
     * 获取连接池客户端
     *
     * @return
     */
    public final RedisDb getPoolClient(String host, int port, String auth, int maxActive, int maxIdle) {
        RedisConfig c1 = new RedisConfig();
        c1.Host = host;
        c1.Port = port;
        c1.Auth = auth;
        c1.MaxActive = maxActive;
        c1.MaxIdle = maxIdle;

        JedisPoolConfig c = new JedisPoolConfig();
        c.setMaxTotal(c1.MaxActive);
        c.setMaxIdle(c1.MaxIdle);
        c.setMaxWaitMillis(c1.MaxWait);
        c.setTestOnBorrow(c1.TestOnBorrow);

        JedisPool pool = new JedisPool(c, c1.Host, c1.Port, c1.TimeOut, c1.Auth);
        Jedis redisclient = pool.getResource();
        RedisDb db = new RedisDb(redisclient, pool);
        return db;
    }

    /**
     * 独立创建一个客户端
     *
     * @param hostip
     * @param port
     * @param password
     * @return
     */
    public final RedisDb createClient(String hostip, int port, String password) {
        Jedis client = new Jedis(hostip, port);
        if (!StringUtils.isEmpty(password)) {
            client.auth(password);
        }
        RedisDb db = new RedisDb(client);
        return db;
    }
}